package share

import (
	"clouds.lgb24kcs.cn/controllers/share/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/oss"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
)

type ListShareAPI struct {
}

var ListAPI ListShareAPI

func (l *ListShareAPI) ListShare(c *gin.Context, req request.ListShareReq, userId int64) {

	//global.APP.DB.Where("user_id=?",userId)
	shareInfo := []models.Share{}
	var Count int64
	fmt.Println(req.Limit, req.Page)
	scan := global.APP.DB.Raw("SELECT * FROM shares WHERE user_id=?  and deleted_at IS Null LIMIT ?,?", userId, req.Limit-1, req.Page).Scan(&shareInfo).Count(&Count)
	//scan := global.APP.DB.Find(&shareInfo).Count(&Count)
	//scan := global.APP.DB.Limit(int(req.Page)).Offset(int(req.Limit - 1)).Find(&shareInfo).Count(&Count)

	if scan.Error != nil {
		global.APP.Log.Error(fmt.Sprintf("分页查询失败：%s", scan.Error.Error()))
		utils.Fail(c, errorx.ShareLists, "分享数据加载失败")
	} else if scan.RowsAffected == 0 {
		global.APP.Log.Error(fmt.Sprintf("分页查询失败：%s", "分享查询结果为空"))
		utils.Fail(c, errorx.ObjectList, "分享数据加载失败")
	} else {
		bucketInfo := models.Storage{}
		tx := global.APP.DB.Where("userid=?", userId).First(&bucketInfo)
		if scan.Error != nil {
			global.APP.Log.Error(tx.Error.Error())

			utils.Fail(c, errorx.ShareLists, "分享数据加载失败")

		} else {
			o := oss.OSS{}
			client := o.NewClient(bucketInfo.Accesskey, bucketInfo.Secretkey, bucketInfo.Zone)
			shareLists := []request.ListsResp{}
			for _, item := range shareInfo {
				exists := o.ObjectExists(client, strings.Split(item.ShareName, "/")[0], strings.Split(item.ShareName, "/")[1]+"/"+strings.Split(item.ShareName, "/")[2])
				if exists {
					shareLists = append(shareLists, request.ListsResp{
						Id:         int64(item.ID),
						UserID:     int64(item.UserID),
						ShareName:  item.ShareName,
						Expiration: item.Expiration,
						ShareURL:   item.ShareURL,
						CreateAt:   item.CreatedAt.Format(time.DateTime),
					})
				} else {
				}
			}
			utils.Success(c, Count, shareLists)
		}
	}
}
